// import {
//   // getDynamicForm,
//   getParentHeader
// } from '@/api/dynamicInterface';
/* eslint-disable no-labels */
/* eslint-disable no-unused-vars */
import _ from 'lodash';
// import { changeValueKey } from '@/utils/commonMethods';
export const TabsTableMixins = {
  methods: {
    initPage() {
      const { menuId, formGuid } = this;
      this.getHeader({
        menuId,
        formGuid
      }).then(res => {
        this.$emit('getDataSource', res);
        if (res.success) {
          this.parentHeaderData = res.data;
          const tabInfo = res.data.childrenTableInfos;
          // 默认点击第一下
          if (tabInfo && tabInfo.length) {
            const data = tabInfo[0];
            const obj = { '$attrs': { data }};
            this.tabClick(obj);
            this.specialHeaderDate = res.data.childrenTableInfos;
            // 不显示该页签
            this.parentHeaderData.childrenTableInfos = this.parentHeaderData.childrenTableInfos.filter(item => item.display !== 0);
          }
        }
      });
    },

    validate() {
      const validate = new Promise((resolve, reject) => {
        let message = '';
        const keys = Object.keys(this.form);
        const rules = [];
        // 所有必填字段
        const allRequireBTZD = [];
        // 获取验证规则
        for (let i = 0; i < keys.length; i++) {
          const value = this.form[keys[i]];
          if ([3, 4, 5, 6, 13].includes(value.tableType)) {
            value.headers.forEach(item => {
              const rule = {
                rule: {}
              };
              if (Number(item.isRequired) === 1) {
                rule['rule']['isRequired'] = true;
              }
              if (Number(item.isRules)) {
                rule['rule']['isRules'] = Number(item.isRules);
                if (item.ruleFormula) {
                  rule['rule']['ruleFormula'] = item.ruleFormula;
                }
              }
              if (JSON.stringify(rule['rule']) !== '{}') {
                rules.push({
                  ...rule,
                  key: keys[i],
                  tableName: value.tableName,
                  lable: item.title,
                  value: item.dataIndex
                });
              }
            });
          }
          if (value.BTZD) {
            allRequireBTZD.push(keys[i]);
          }
        }
        frist:
        for (let i = 0; i < rules.length; i++) {
          const form = this.form[rules[i].key];
          for (let j = 0; j < form.bodys.length; j++) {
            if (Number(rules[i].rule.isRequired)) {
              if (!form.bodys[j][rules[i].value]) {
                message = `${rules[i].tableName}第${j + 1}行的${rules[i].lable}未填写`;
                break frist;
              }
            } else {
              // 不是必填,切没有填写不触发验证
              if (!form.bodys[j][rules[i].value]) {
                continue;
              }
            }
            const item = form.bodys[j];
            if (rules[i].rule.isRules === 1) {
              const ruleFormula = rules[i].rule.ruleFormula;
              if (!eval(ruleFormula.formula)) {
                message = `${rules[i].tableName}第${j + 1}行${ruleFormula.errorMessage}`;
                break frist;
              }
            } else if (rules[i].rule.isRules === 2) {
              const ruleFormula = rules[i].rule.ruleFormula;
              const arr = [];
              ruleFormula.data.forEach(item => {
                arr.push(item.key);
              });
              eval('var ' + arr.join(','));
              for (let k = 0; k < ruleFormula.data.length; k++) {
                const dataKey = ruleFormula.data[k].key;
                // [3, 4, 5, 6, 13] 表单样式
                if ([3, 4, 5, 6, 13].includes(ruleFormula.data[k].tableType)) {
                  const bodys = this.form[ruleFormula.data[k].tableId].bodys;
                  const total = bodys.reduce((sum, e) => sum + Number(e[dataKey]), 0);
                  window.eval('var ' + dataKey + '=' + total);
                } else if ([1, 2].includes(ruleFormula.data[k].tableType)) {
                  const headers = this.form[ruleFormula.data[k].tableId].headers;
                  headers.forEach(item => {
                    if (item.dataIndex === ruleFormula.data[k].key) {
                      window.eval('var ' + dataKey + ' = ' + Number(item.myValue));
                    }
                  });
                }
              }
              if (!eval(ruleFormula.formula)) {
                message = ruleFormula.errorMessage;
                break frist;
              }
            }
          }
        }

        // 验证创建需要全部都写
        if (!this.formGuid) {
          const data = this.parentHeaderData.childrenTableInfos;
          for (let i = 0; i < data.length; i++) {
            if (Number(data[i].isHaveRequiredFields)) {
              if (!this.form[data[i].id] && ![9, 11].includes(Number(data[i].tableType))) {
                message = `请先填写${data[i].tableName}`;
                break;
              } else if ([9, 11].includes(Number(data[i].tableType))) {
                if (!this.form[data[i].id] || !this.form[data[i].id].bodys.length) {
                  message = `请先上传${data[i].tableName}`;
                  break;
                }
              }
            }
          }
        }

        // 校验表单
        if (!message) {
          message = this.checkFormData();
        }

        // 校验跨表所有字段必填BTZD
        if (!message && allRequireBTZD.length) {
          message = this.allRequireByBTZD(allRequireBTZD, this.form);
        }

        const form = [];
        const file = [];
        const tableIdArr = Object.keys(this.form);
        tableIdArr.forEach(item => {
          let data = [];
          const formType = [3, 4, 5, 6, 8, 9, 11, 13, 21, 22];
          const tableType = this.form[item].tableType;
          // 添加附件参数file
          if ([9, 11, 21, 22].includes(tableType)) {
            // file = this.form[item].bodys.filter(item => item.file);
            const fileArr = this.form[item].bodys.filter(item => item.file);
            // fileArr.forEach(item => {
            //   item.id && delete item.id;
            //   item.saveName && delete item.saveName;
            //   item.fileName && delete item.fileName;
            //   item.RN && delete item.RN;
            // });
            file.push({
              file: fileArr,
              description: this.form[item].tableId
            });
          }
          // 创建表单表格
          if (!this.formGuid && (tableType === 1 || tableType === 2)) {
            const obj = {};
            this.form[item].headers.forEach(item => {
              obj[item.dataIndex] = item.myValue;
              // const { myValue } = item;
              // 有选项需要转换
              // obj[item.dataIndex] = changeValueKey(item, myValue);
            });
            data.push(obj);
          } else if (this.formGuid && (tableType === 1 || tableType === 2)) {
            const obj = {};
            this.form[item].headers.forEach(item => {
              if (item.editMark) {
                obj[item.dataIndex] = item.myValue;
                // const { myValue } = item;
                // 有选项需要转换
                // obj[item.dataIndex] = changeValueKey(item, myValue);
              }
            });
            Object.keys(obj).length && data.push({
              ...obj,
              rowNum: this.form[item].bodys[0].ROW_NUM,
              option: 'update'
            });
          } else if (formType.includes(tableType) && !this.formGuid) {
            const fileBody = _.cloneDeep(this.form[item].bodys);
            const dealArr = [];
            fileBody.forEach(body => {
              let bool = false;
              body.file && delete body.file;
              for (const key in body) {
                key !== 'id' && key !== 'RN' && body[key] && (bool = true);
                // const findItem = this.form[item].headers.find(i => i.dataIndex === key);
                // body[key] = findItem ? changeValueKey(findItem, body[key]) : body[key];
              }
              bool && dealArr.push(body);
            });
            data = dealArr;
            // if (fileBody.length === 1) {
            //   let bool = false;
            //   for (const i in fileBody[0]) {
            //     i !== 'id' && i !== 'RN' && fileBody[0][i] && (bool = true);
            //   }
            //   bool && (data = fileBody);
            // } else {
            //   data = fileBody;
            // }
          } else if (formType.includes(tableType) && !!this.formGuid) {
            const oldBodyId = [];
            const newBodyId = [];
            const deleteId = [];
            this.form[item].changeBodys.forEach(v => oldBodyId.push(v.id));
            this.form[item].bodys.forEach(v => newBodyId.push(v.id));
            oldBodyId.forEach((itemOld, index) => {
              const i = newBodyId.findIndex(itemNew => itemOld === itemNew);
              if (i !== -1) {
                const obj = {
                  option: 'update',
                  rowNum: this.form[item].bodys[i]['ROW_NUM']
                };
                const keys = Object.keys(this.form[item].bodys[i]);
                keys.forEach(key => {
                  if ((this.form[item].bodys[i][key] + '') !== (this.form[item].changeBodys[index][key] + '') && key !== 'file') {
                    obj[key] = this.form[item].bodys[i][key];
                    // const findItem = this.form[item].headers.find(i => i.dataIndex === key);
                    // findItem && (obj[key] = changeValueKey(findItem, obj[key]));
                    // obj[key] = findItem ? changeValueKey(findItem, obj[key]) : obj[key];
                  }
                });
                Object.keys(obj).length !== 2 && data.push(obj);
                deleteId.push(itemOld);
              } else {
                const obj = {
                  option: 'delete',
                  rowNum: this.form[item].changeBodys[index]['ROW_NUM']
                };
                data.push(obj);
              }
            });
            newBodyId.forEach((itemdel, index) => {
              const i = deleteId.findIndex(itemNew => itemdel === itemNew);
              const fileBody = _.cloneDeep(this.form[item].bodys[index]);
              fileBody.file && delete fileBody.file;
              if (i === -1) {
                let bool = false;
                for (const key in fileBody) {
                  key !== 'id' && key !== 'RN' && fileBody[key] && (bool = true);
                  // const findItem = this.form[item].headers.find(i => i.dataIndex === key);
                  // fileBody[key] = findItem ? changeValueKey(findItem, fileBody[key]) : fileBody[key];
                }
                bool && (data.push({
                  option: 'create',
                  ...fileBody
                }));
                // data.push({
                //   option: 'create',
                //   ...fileBody
                // });
              }
            });
          }
          if (data.length) {
            form.push({
              tableId: item,
              data
            });
          }
        });
        if (!message) {
          resolve({
            success: true,
            data: form,
            file
          });
        } else {
          resolve({
            success: false,
            message,
            data: form,
            file
          });
        }
      });
      return validate;
    },

    checkFormData() {
      let [flag, msg] = [false, ''];

      const brr = this.getFormValues();
      const arr = this.getFormKeys();

      const parseMap = {
        int: item => item * 1,
        string: item => `'${item}'`,
        date: item => new Date(item).getTime()
      };
      const deepSearch = function(data, key, res) {
        if (res.value) {
          return;
        } else {
          if (Array.isArray(data) && data.length) {
            data.forEach(item => deepSearch(item, key, res));
          } else {
            if (data.dataIndex === key) {
              res.value = data;
            } else if (data.children) {
              deepSearch(data.children, key, res);
            }
          }
        }
      };
      for (let i = 0; i < brr.length; i++) {
        const item = brr[i];
        if (item === undefined) {
          if (!this.formGuid) {
            // 提交申请
            if (!arr[i].isHaveRequiredFields) {
              break;
            } else {
              msg = '请将' + arr[i].tableName + '填写完整';
              flag = true;
              return msg;
            }
          } else {
            break;
          }
        }

        const data = item.headers;
        if (flag) {
          break;
        }
        for (let j = 0; j < data.length; j++) {
          const ele = data[j];
          //
          if (ele.isRules === 1) { // 表内校验
            const {
              ruleType,
              regular,
              errorMessage,
              formula,
              data: col,
              fieldType // string date int
            } = ele.ruleFormula;
            let flag = true;
            if (!errorMessage) {
              msg = '字段：' + ele.title + ',后台配置错误(校验公式中 errorMessage 字段为空或不存在)';
              flag = true;
            }

            if (ruleType === 1) { // 1 正则校验  0 公式校验
              try {
                const reg = new RegExp(regular);
                if (!reg.test(ele.myValue)) {
                  msg = errorMessage;
                  flag = true;
                  break;
                }
              } catch (error) {
                flag = true;
                msg = '字段：' + ele.title + ',后台配置错误(校验公式中 regular 字段配置错误)';
              }
            }

            if (ruleType === 0) {
              const searchRes = col.map(item1 => {
                const res = {};
                deepSearch(item.headers, item1.key, res);
                if (!res.value) {
                  msg = `字段：${ele.title} 中,后台配置错误(校验公式data中), 未匹配到${item1.key}字段`;
                  flag = true;
                }
                return res.value;
              });
              console.log(ele.ruleFormula);
              console.log(ele.ruleFormula.fieldType);
              console.log(fieldType, ele.title);
              if (!fieldType || !['int', 'string', 'date'].includes(fieldType)) {
                msg = '字段：' + ele.title + ',后台配置错误(校验公式中 fieIdType 字段应该为 [int, string, date] 其中之一';
              }

              if (msg) {
                return msg;
              }

              if (searchRes.some(item => item)) {
                // searchRes.length = 3;
                searchRes.forEach(v => {
                  window.eval(`var ${v.dataIndex} = ${parseMap[fieldType](v.myValue)};`);
                });

                try {
                  flag = !(eval(formula));
                  if (flag) {
                    msg = errorMessage;
                    // msg = errorMessage + ': ' + formula;
                  }
                } catch (error) {
                  flag = true;
                  msg = '执行' + formula + ' 错误';
                }
              }

              /* const regOpterator = /[\/\*()+-<>=0-9]+/g; // 匹配运算符号
                const regLetter = /[a-zA-Z_]{1,}/g; // 匹配keys  (key不能包涵数字)

                const keys = formula.match(regLetter);
                const operator = formula.match(regOpterator);

                const regArr = keys.map(regKey => {
                  const regFind = data.find(dataItem => {
                    return dataItem.dataIndex === regKey;
                  });
                  if (!regFind) {
                    flag = false;
                    this.$message.warning('没有检索到:' + regKey + ' ,请确认配置是否正确');
                  }
                  return regFind;
                });

                let continueCompare = true;
                regArr.forEach(item => { // 有一项为空则不再进行比较
                  if (item.myValue === '' || item.myValue === null) {
                    continueCompare = false;
                  }
                });

                if (flag && continueCompare) {
                  let compareArr = regArr.map(item => item.myValue);
                  const parseMap = {
                    int: item => item * 1,
                    string: item => `'${item}'`,
                    date: item => new Date(item).getTime()
                  };
                  if (fieldType in parseMap) {
                    compareArr = compareArr.map(item => {
                      return parseMap[fieldType](item);
                    });
                  }

                  const resultArr = [];
                  const msgArr = [];
                  compareArr.forEach((item, index) => {
                    if (operator[0] === '(') {
                      resultArr.push(operator[index]);
                      resultArr.push(item);
                      msgArr.push(...[operator[index], regArr[index].title]);
                    } else {
                      const oper = operator[index];
                      resultArr.push(item);
                      if (oper) {
                        resultArr.push(oper);
                      }
                      msgArr.push(...[regArr[index].title, oper && oper]);
                    }
                  });
                  const result = eval(resultArr.join(''));

                  if (!result) {
                    flag = true;
                    msg = `校验失败: ${item.tableName}中, ${ele.ruleFormula.errorMessage}`;
                    break;
                  }
                } */
            }
          }
          if (ele.isRequired === 1 && ele.myValue === '' && ele.componentType !== '') {
            if (item.tableType === 2) {
              if (/（填）$/.test(ele.title)) {
                msg = `${item.tableName}中的 '${ele.title}' 属性不能为空`;
                flag = true;
                break;
              }
            } else {
              msg = `${item.tableName}中的 '${ele.title}' 属性不能为空`;
              flag = true;
              break;
            }
          }
        }
      }
      return msg;
    },

    allRequireByBTZD(arr, obj) {
      let message;
      arr.forEach(i => {
        // 获取pc显示的字段全必填
        const headersArr = obj[i].headers.map(i => i.dataIndex);
        obj[i].bodys.forEach((v, index) => {
          const objKeys = Object.keys(v);
          objKeys.forEach(key => {
            if (headersArr.includes(key) && !v[key]) {
              message = `请将${obj[i].tableName}的第${index + 1}行所有数据填写完整`;
            }
          });
        });
      });
      return message;
    },

    // 获取表单的key
    getFormKeys() {
      return this.parentHeaderData.childrenTableInfos.filter(item => {
        return item.tableType === 1 || item.tableType === 2;
      });
    },

    // 获取表单的数组内容
    getFormValues() {
      return this.getFormKeys().map(item => {
        return this.form[item.id];
      });
    }

  }
};
